package oa.core;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;

public class MyCookie {
	
	private static Cookie cookie = null;



	public static Cookie getInstance(String cookieName, String cookieValue){
		if(cookie == null){
			return new Cookie(cookieName, cookieValue);
		}
		return cookie;
	}
	
	public static void setDomain(String domain){
		if(domain == null){
			MyCookie.cookie.setDomain("");
		}else{
			MyCookie.cookie.setDomain(domain);
		}
	}
	
	public static void setMaxAge(int maxAge){
		//if the set not use cookie
		if(maxAge == 0){
			MyCookie.cookie.setMaxAge(0);
		}else{
			MyCookie.cookie.setMaxAge(Constant.COOKIE_MAX_AGE);
		}
	}

    public static Cookie getCookie(String cookieName, HttpServletRequest request){
        Cookie cookies[] = request.getCookies();
        if(cookies == null || cookies.length == 0){
            return null;
        }
        for(int i=0; i<cookies.length; i++){
            if(cookies[i] !=null){
                //System.out.println(cookies[i].getName()+cookies[i].getValue());
                if(cookies[i].getName().equals(cookieName)){
                    return cookies[i];
                }
                continue;
            }
        }
        return null;
    }

    public static Cookie addCookie(String cookieName, String value, String domain, String path, int age){
        if(cookieName==null|| cookieName.equals("")){
            return null;
        }
        if(domain==null || domain.equals("")){
            domain = Constant.COOKIE_DOMAIN;
        }

        if(path == null || path.equals("")){
            path = Constant.COOKIE_PATH;
        }

        if(age != -1){
            age = Constant.COOKIE_TRANSIENT_AGE;
        }

        Cookie cookie = new Cookie(cookieName,value);
        cookie.setDomain(domain);
        cookie.setPath(path);
        cookie.setMaxAge(age);
        return cookie;
    }

	
}
